package org.finmanager.core;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import static org.finmanager.core.Constants.*;

/**
 * Created by Kelvin on 22/3/2014.
 * <p/>
 * Just a simple frame for adding category
 * <p/>
 * May expand for more functions later
 */

//Tpying the "+" in the "Cat" window in the budget function will pop up this simple frame
public class CategoryInputUI {
	private JPanel mainPanel = new JPanel();

	private JFrame frame;

	private JTextField nameTextField;

	private JButton okayButton;

	public CategoryInputUI(CategoryManagerController categoryManagerController) {

		createAndShowGUI(categoryManagerController.getItemManagerController().getUIMainComponent());
	}

	public JComponent getMainComponent() {
		return mainPanel;
	}

	private void createAndShowGUI(JComponent relative) {

		JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 5));
		inputPanel.setBorder(BorderFactory.createEmptyBorder(10, 0 ,10, 0));

		nameTextField = new JTextField("", 10);

		inputPanel.add(nameTextField);

		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));

		okayButton = new JButton("OK");
		JButton cancelButton = new JButton("Cancel");

		okayButton.addActionListener(new CloseWindowListener());
		okayButton.setActionCommand(CategoryManagerController.ADD_CATEGORY);
		cancelButton.addActionListener(new CloseWindowListener());

		buttonPanel.add(okayButton);
		buttonPanel.add(cancelButton);

		getMainComponent().setLayout(new BorderLayout(0, 0));
		getMainComponent().add(inputPanel, BorderLayout.CENTER);
		getMainComponent().add(buttonPanel, BorderLayout.SOUTH);


		frame = new JFrame(CATEGORY_INPUT_UI_NAME);
		frame.setSize(new Dimension(CATEGORY_INPUT_UI_WIDTH, CATEGORY_INPUT_UI_HEIGHT));
		frame.setLocationRelativeTo(relative);
		frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		frame.setResizable(CATEGORY_INPUT_UI_RESIZABLE);

		frame.add(getMainComponent());

		frame.setVisible(true);
	}

	public void addButtonListener(ActionListener listener) {
		okayButton.addActionListener(listener);
	}

	public String getNameTextField() {
		return nameTextField.getText();
	}

	private class CloseWindowListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			frame.dispose();
		}
	}
}
